﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace zy_simu.Data
{
    internal class CommPkg
    {
        static public int head_size = 8;
        private byte[] buf;
        public CommPkg(ref byte[] buf)
        {
            this.buf = buf;
            data = buf[head_size..];
        }
        public byte flag                // 0xAA flag
        {
            get { return buf[0]; }
            set { buf[0] = value; }
        }
        public byte cmd
        {
            get { return buf[1]; }
            set { buf[1] = value; }
        }
        public ushort len
        {
            get { return (ushort)(buf[2] + (buf[3] << 8)); }
            set { buf[2] = (byte)(value & 0xff); buf[3] = (byte)((value & 0xff00) >> 8); }
        }
        public uint checksum       // 整包数据含ZqCommPkg结构校验
        {
            get { return (uint)(buf[4] + (buf[5] << 8) + (buf[6] << 16) + (buf[7] << 24)); }
            set { buf[4] = (byte)(value & 0xff); buf[5] = (byte)((value & 0xff00) >> 8); buf[6] = (byte)((value & 0xff0000) >> 16); buf[7] = (byte)((value & 0xff000000) >> 24); }
        }
        public byte[] data;

        public static uint GetChecksum(byte[] data, uint len)
        {
            uint s = 0;
            for (int i = 0; i < len; i++)
            {
                s += ((uint)data[i] << ((i % 4) * 8));
            }
            return s;
        }
        public static byte GetChecksum8(byte[] data, uint len)
        {
            byte s = 0;
            for (int i = 0; i < len; i++)
            {
                s ^= data[i];
            }
            return s;
        }
    }
}
